"""
不同周期的波动率因子 （归一化处理 ）
1分钟周期取6 12 24 48 96  （归一化处理 ）
波动率用ATR算法（为了弱化跳空影响 atr只用high-low）
分别取值6根k线的atr 12根k线的atr ……
"""
import pandas as pd
import rqdatac as rq
from datetime import timedelta
from ..utility import make_domaint_time_dict


def self_get_factor_df(sec_id):
    symbol_time_dict = make_domaint_time_dict(sec_id)
    result_df = {}
    prices_df = {}
    for symbol, time_dict in symbol_time_dict.items():
        prices = rq.get_price(symbol, start_date="20220801", end_date="20231116", frequency="1m",
                              fields=["close", "high", "low"], expect_df=False)
        prices.index -= timedelta(minutes=1)
        prices["atr"] = ((prices["high"] - prices["low"]) / prices["low"]).rolling(1000).mean()
        symbol_df = pd.DataFrame()
        for window in [6, 12, 24, 48, 96]:
            prices[f"atr_{window}"] = ((prices["high"] - prices["low"]) / prices["low"]).rolling(window).mean()
            prices[f"atr_rate_{window}"] = prices[f"atr_{window}"] / prices["atr"]
            symbol_df[f"atr_rate_{window}"] = prices[f"atr_rate_{window}"]
        prices = prices[time_dict["start"]: time_dict["last"]]
        symbol_df = symbol_df[time_dict["start"]: time_dict["last"]]
        symbol_df["symbol"] = symbol
        prices["symbol"] = symbol
        result_df[symbol] = symbol_df
        prices_df[symbol] = prices
    return pd.concat(list(result_df.values())), pd.concat(list(prices_df.values()))


def get_factor_df(sec_id, prices):
    print(sec_id, __file__)
    atr = ((prices["high"] - prices["low"]) / prices["low"]).rolling(1000).mean()
    for window in [6, 12, 24, 48, 96]:
        atr1 = ((prices["high"] - prices["low"]) / prices["low"]).rolling(window).mean()
        prices[f"atr_{window}"] = atr1 / atr
    return prices
